//
//  ZCOrderListVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/3/2.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "ZCOrderListVC.h"

#import "ZCOrderListBodyVC.h"
#import "ZCOrderViewModel.h"
#import "PaymentManager.h"
#import <Masonry.h>
#import "SYLoginVC.h"

@interface ZCOrderListVC ()<UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *toolBarView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *line;



@end

@implementation ZCOrderListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self initNetData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)initNetData {
    if (self.index != 0) {
        [self.scrollView setContentOffset:(CGPoint){self.index * ScreenWidth,0} animated:YES];
    } else {
        UIButton *btn = [self.toolBarView viewWithTag:10 + self.index];
        [self updateLineWithBtn:btn];
    }
}

- (void)setupUI {
    self.navTitle = @"我的订单";
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    self.scrollView.contentSize = CGSizeMake(ScreenWidth * 5, 0);
    NSMutableArray *views = [NSMutableArray new];
    __weak typeof(self) weakSelf = self;
    for (NSInteger i = 0; i < 5; i++) {
        ZCOrderListBodyVC *vc = [[ZCOrderListBodyVC alloc] init];
        [self addChildViewController:vc];
        [self.scrollView addSubview:vc.view];
        [views addObject:vc.view];
        if (i == 0) {
            vc.status = -1;
        }
        if (i == 1) {
            vc.status = 1;
        }
        if (i == 2) {
            vc.status = 2;
        }

        if (i == 3) {
            vc.status = 3;
        }

        if (i == 4) {
            vc.status = 5;
        }

        [vc setRefreshCallBack:^(NSInteger status, NSString * _Nonnull lastId) {
            [weakSelf netFetchOrderListWithStatus:status lastId:lastId keywd:nil];
        }];
        
        [vc setLoadMoreCallBack:^(NSInteger status, NSString * _Nonnull lastId) {
            [weakSelf netFetchOrderListWithStatus:status lastId:lastId keywd:nil];
        }];
        
        [vc setSearchCallBack:^(NSInteger status, NSString *lastId, NSString *keywd) {
            [weakSelf netFetchOrderListWithStatus:status lastId:lastId keywd:keywd];
        }];
        
        [vc setNeedUpdateData:^(NSInteger status) {
            for (ZCOrderListBodyVC *kvc in weakSelf.childViewControllers) {
                if (kvc.status != status) {
                    [kvc updateDataSource];
                }
            }
        }];
    }
    [views mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    [views mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.scrollView.mas_height);
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(ScreenWidth);
    }];
}

- (void)basePopAction {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)updateLineWithBtn:(UIButton *)btn {
    self.index = btn.tag % 10;
    [self.line mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(2);
        make.centerX.mas_equalTo(btn.mas_centerX);
    }];
    [UIView animateWithDuration:0.1 animations:^{
        [self.toolBarView layoutIfNeeded];
    }];
    
    for (UIButton *kbtn in self.toolBarView.subviews) {
        if (kbtn.tag >= 10) {
            kbtn.selected = NO;
        }
    }
    btn.selected = YES;
    ZCOrderListBodyVC *vc = self.childViewControllers[self.index];
    [vc beginRefresh];
}

// MARK: - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        NSInteger index = scrollView.contentOffset.x / ScreenWidth;
        UIButton *btn = [self.toolBarView viewWithTag:10 + index];
        [self updateLineWithBtn:btn];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        NSInteger index = scrollView.contentOffset.x / ScreenWidth;
        UIButton *btn = [self.toolBarView viewWithTag:10 + index];
        [self updateLineWithBtn:btn];
    }
}


// MARK: - Action

- (IBAction)tagBtnClickAction:(UIButton *)sender {
    [self.scrollView setContentOffset:(CGPoint){sender.tag % 10 * ScreenWidth,0}
                             animated:YES];
}

// MARK: - NET

- (void)netFetchOrderListWithStatus:(NSInteger)status lastId:(NSString *)lastId keywd:(NSString *)keywd {
    __block BOOL issearch = keywd != nil;
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCOrderViewModel fetchOrderListWithStatus:status pageSize:10 lastItemid:lastId keywd:keywd complete:^(ZCErrorCode status, NSString *message, id data) {
      dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
      });
        if (status == kHXSNoError) {
            NSArray *items = [data valueForKey:@"items"];
            ZCOrderListBodyVC *vc = self.childViewControllers[weakSelf.index];
            if (vc.lastId != nil && items.count == 0) {
                [weakSelf.view makeToast:@"没有更多了" duration:2.0 position:CSToastPositionCenter];
            }
            vc.items = [data valueForKey:@"items"];
            vc.lastId = [data valueForKey:@"id"];
            [vc reloadDataWithSearch:issearch];
        } else if(status == kHXSInvalidTokenError) {
          weakSelf.userModel = nil;
          ZCBaseUserManager *manager = [ZCBaseUserManager shareInstance];
          manager.userModel = nil;
            SYLoginVC *vc = [[SYLoginVC alloc] init];
          __weak typeof(self) weakSelf = self;
          vc.dismissCallback = ^{
            [weakSelf initNetData];
          };
            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
            [nvc setModalPresentationStyle:UIModalPresentationOverFullScreen];
            [weakSelf.view.window.rootViewController presentViewController:nvc animated:YES completion:nil];
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)managerDidRecvMiniResponse:(WXLaunchMiniProgramResp *)response {
    switch (response.errCode) {
        case WXSuccess: {
            [self.view makeToast:@"支付成功" duration:2.0 position:CSToastPositionCenter];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UIButton *btn = [self.toolBarView viewWithTag:10 + self.index];
                [self updateLineWithBtn:btn];
            });
        }
            break;
        case WXErrCodeUserCancel: {
            [self.view makeToast:@"支付取消了" duration:2.0 position:CSToastPositionCenter];
        }
            break;
        default:{
            [self.view makeToast:@"支付失败" duration:2.0 position:CSToastPositionCenter];
        }
            break;
    }
}

@end
